// WebSocket连接
let socket;
let temperatureChart, smokeChart;
let sensorData = {};

// 初始化应用
document.addEventListener('DOMContentLoaded', function() {
    initWebSocket();
    initCharts();
    updateDateTime();
    setInterval(updateDateTime, 1000);
    
    // 绑定按钮事件
    bindActionButtons();
});

// 初始化WebSocket连接
function initWebSocket() {
    socket = io();
    
    socket.on('connect', function() {
        console.log('WebSocket连接成功');
        updateConnectionStatus(true);
    });
    
    socket.on('disconnect', function() {
        console.log('WebSocket连接断开');
        updateConnectionStatus(false);
    });
    
    socket.on('data_update', function(data) {
        console.log('收到数据更新:', data);
        handleDataUpdate(data);
    });
    
    socket.on('connected', function(data) {
        console.log('服务器确认连接:', data);
    });
}

// 处理数据更新
function handleDataUpdate(update) {
    const { type, data, timestamp } = update;
    
    switch(type) {
        case 'initial_data':
        case 'requested_data':
            sensorData = data;
            updateAllDisplays();
            break;
            
        case 'mqtt_data':
            updateMqttData(update);
            break;
            
        case 'system_action':
            sensorData = data;
            updateAllDisplays();
            showNotification(`系统操作: ${update.action}`, 'info');
            break;
    }
}

// 更新MQTT数据
function updateMqttData(update) {
    const { topic, data } = update;
    
    if (topic.includes('temperature')) {
        updateZoneTemperature(data.zone, data.value);
    } else if (topic.includes('smoke')) {
        updateZoneSmoke(data.zone, data.value);
    } else if (topic.includes('alarm')) {
        addAlarmToList(data);
    }
    
    updateCharts();
}

// 更新所有显示
function updateAllDisplays() {
    updateSystemOverview();
    updateZoneStatus();
    updateDeviceStatus();
    updateStatistics();
    updateAlarmLog();
    updateCharts();
}

// 更新系统总览
function updateSystemOverview() {
    if (!sensorData.system) return;
    
    const system = sensorData.system;
    const zones = sensorData.zones || {};
    
    // 计算平均温度
    const avgTemp = Object.values(zones).reduce((sum, zone) => sum + zone.temperature, 0) / Object.keys(zones).length;
    const avgSmoke = Object.values(zones).reduce((sum, zone) => sum + zone.smoke, 0) / Object.keys(zones).length;
    
    // 更新显示
    updateOverviewItem('系统状态', system.status === 'normal' ? '正常' : '异常', system.status);
    updateOverviewItem('平均温度', `${avgTemp.toFixed(1)}°C`);
    updateOverviewItem('烟雾浓度', `${(avgSmoke * 100).toFixed(2)}%`);
    updateOverviewItem('灭火剂压力', '1.2MPa');
}

// 更新总览项目
function updateOverviewItem(label, value, status = 'normal') {
    const items = document.querySelectorAll('.overview-item');
    items.forEach(item => {
        const labelElement = item.querySelector('.overview-label');
        if (labelElement && labelElement.textContent === label) {
            const valueElement = item.querySelector('.overview-value');
            const iconElement = item.querySelector('.overview-icon');
            
            if (valueElement) {
                valueElement.textContent = value;
                valueElement.className = `overview-value ${status}`;
            }
            
            if (iconElement) {
                iconElement.className = `overview-icon ${status}`;
            }
        }
    });
}

// 更新区域状态
function updateZoneStatus() {
    if (!sensorData.zones) return;
    
    Object.entries(sensorData.zones).forEach(([zoneId, zoneData]) => {
        const zoneElement = document.querySelector(`[data-zone="${zoneId}"]`);
        if (zoneElement) {
            // 更新传感器状态
            const sensors = zoneElement.querySelectorAll('.sensor');
            sensors.forEach(sensor => {
                const status = getZoneStatus(zoneData);
                sensor.className = `sensor ${sensor.classList[1]} ${status}`;
            });
            
            // 更新区域背景色
            zoneElement.style.borderColor = getStatusColor(getZoneStatus(zoneData));
        }
    });
}

// 获取区域状态
function getZoneStatus(zoneData) {
    if (zoneData.temperature > 50 || zoneData.smoke > 0.1) {
        return 'danger';
    } else if (zoneData.temperature > 35 || zoneData.smoke > 0.05) {
        return 'warning';
    }
    return 'normal';
}

// 获取状态颜色
function getStatusColor(status) {
    switch(status) {
        case 'danger': return '#ff4444';
        case 'warning': return '#ffaa00';
        default: return 'rgba(0, 212, 255, 0.3)';
    }
}

// 更新设备状态
function updateDeviceStatus() {
    if (!sensorData.devices) return;
    
    const deviceMapping = {
        'main_controller': '主控制器',
        'communication': '通信模块',
        'backup_power': '备用电源',
        'water_pump': '水泵系统'
    };
    
    Object.entries(sensorData.devices).forEach(([deviceId, deviceData]) => {
        const deviceName = deviceMapping[deviceId];
        if (deviceName) {
            updateDeviceItem(deviceName, deviceData.message, deviceData.status);
        }
    });
}

// 更新设备项目
function updateDeviceItem(name, message, status) {
    const items = document.querySelectorAll('.device-item');
    items.forEach(item => {
        const nameElement = item.querySelector('.device-name');
        if (nameElement && nameElement.textContent === name) {
            const statusElement = item.querySelector('.device-status-text');
            const iconElement = item.querySelector('.device-icon');
            
            if (statusElement) {
                statusElement.textContent = message;
                statusElement.className = `device-status-text ${status}`;
            }
            
            if (iconElement) {
                iconElement.className = `device-icon ${status}`;
            }
        }
    });
}

// 更新统计信息
function updateStatistics() {
    if (!sensorData.system) return;
    
    const system = sensorData.system;
    updateStatItem('传感器总数', system.total_sensors);
    updateStatItem('喷淋头数量', system.sprinklers);
    updateStatItem('今日报警次数', system.today_alarms);
    updateStatItem('系统可用率', `${system.availability}%`);
}

// 更新统计项目
function updateStatItem(label, value) {
    const items = document.querySelectorAll('.stat-item');
    items.forEach(item => {
        const labelElement = item.querySelector('.stat-label');
        if (labelElement && labelElement.textContent === label) {
            const numberElement = item.querySelector('.stat-number');
            if (numberElement) {
                numberElement.textContent = value;
            }
        }
    });
}

// 更新报警日志
function updateAlarmLog() {
    if (!sensorData.alarms) return;
    
    const logList = document.querySelector('.log-list');
    if (!logList) return;
    
    logList.innerHTML = '';
    
    sensorData.alarms.slice(0, 10).forEach(alarm => {
        const logItem = document.createElement('div');
        logItem.className = `log-item ${alarm.level}`;
        
        logItem.innerHTML = `
            <div class="log-time">${alarm.time}</div>
            <div class="log-content">
                <i class="fas ${getAlarmIcon(alarm.level)}"></i>
                <span>${alarm.message}</span>
            </div>
        `;
        
        logList.appendChild(logItem);
    });
}

// 获取报警图标
function getAlarmIcon(level) {
    switch(level) {
        case 'danger': return 'fa-exclamation-triangle';
        case 'warning': return 'fa-exclamation-circle';
        default: return 'fa-check-circle';
    }
}

// 添加报警到列表
function addAlarmToList(alarmData) {
    if (!sensorData.alarms) {
        sensorData.alarms = [];
    }
    
    const alarm = {
        time: new Date().toLocaleTimeString(),
        message: alarmData.message,
        level: alarmData.level || 'info',
        zone: alarmData.zone || ''
    };
    
    sensorData.alarms.unshift(alarm);
    
    // 保持最多50条记录
    if (sensorData.alarms.length > 50) {
        sensorData.alarms = sensorData.alarms.slice(0, 50);
    }
    
    updateAlarmLog();
    
    // 显示通知
    showNotification(alarm.message, alarm.level);
}

// 初始化图表
function initCharts() {
    // 温度趋势图
    const tempCtx = document.getElementById('temperatureChart');
    if (tempCtx) {
        temperatureChart = new Chart(tempCtx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: 'A区域',
                    data: [],
                    borderColor: '#00d4ff',
                    backgroundColor: 'rgba(0, 212, 255, 0.1)',
                    tension: 0.4
                }, {
                    label: 'B区域',
                    data: [],
                    borderColor: '#00ff88',
                    backgroundColor: 'rgba(0, 255, 136, 0.1)',
                    tension: 0.4
                }, {
                    label: 'C区域',
                    data: [],
                    borderColor: '#ffaa00',
                    backgroundColor: 'rgba(255, 170, 0, 0.1)',
                    tension: 0.4
                }, {
                    label: 'D区域',
                    data: [],
                    borderColor: '#ff4444',
                    backgroundColor: 'rgba(255, 68, 68, 0.1)',
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        labels: {
                            color: '#ffffff'
                        }
                    }
                },
                scales: {
                    x: {
                        ticks: { color: '#888' },
                        grid: { color: 'rgba(255, 255, 255, 0.1)' }
                    },
                    y: {
                        ticks: { color: '#888' },
                        grid: { color: 'rgba(255, 255, 255, 0.1)' }
                    }
                }
            }
        });
    }
    
    // 烟雾浓度图
    const smokeCtx = document.getElementById('smokeChart');
    if (smokeCtx) {
        smokeChart = new Chart(smokeCtx, {
            type: 'bar',
            data: {
                labels: ['A区域', 'B区域', 'C区域', 'D区域'],
                datasets: [{
                    label: '烟雾浓度 (%)',
                    data: [0.02, 0.01, 0.03, 0.02],
                    backgroundColor: [
                        'rgba(0, 212, 255, 0.6)',
                        'rgba(0, 255, 136, 0.6)',
                        'rgba(255, 170, 0, 0.6)',
                        'rgba(255, 68, 68, 0.6)'
                    ],
                    borderColor: [
                        '#00d4ff',
                        '#00ff88',
                        '#ffaa00',
                        '#ff4444'
                    ],
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        labels: {
                            color: '#ffffff'
                        }
                    }
                },
                scales: {
                    x: {
                        ticks: { color: '#888' },
                        grid: { color: 'rgba(255, 255, 255, 0.1)' }
                    },
                    y: {
                        ticks: { color: '#888' },
                        grid: { color: 'rgba(255, 255, 255, 0.1)' },
                        beginAtZero: true
                    }
                }
            }
        });
    }
}

// 更新图表
function updateCharts() {
    if (!sensorData.zones) return;
    
    const now = new Date().toLocaleTimeString();
    
    // 更新温度图表
    if (temperatureChart) {
        const labels = temperatureChart.data.labels;
        labels.push(now);
        
        // 保持最多20个数据点
        if (labels.length > 20) {
            labels.shift();
            temperatureChart.data.datasets.forEach(dataset => {
                dataset.data.shift();
            });
        }
        
        // 添加新数据
        Object.entries(sensorData.zones).forEach(([zoneId, zoneData], index) => {
            temperatureChart.data.datasets[index].data.push(zoneData.temperature);
        });
        
        temperatureChart.update('none');
    }
    
    // 更新烟雾图表
    if (smokeChart) {
        Object.entries(sensorData.zones).forEach(([zoneId, zoneData], index) => {
            smokeChart.data.datasets[0].data[index] = zoneData.smoke * 100; // 转换为百分比
        });
        
        smokeChart.update('none');
    }
}

// 更新区域温度
function updateZoneTemperature(zone, temperature) {
    if (!sensorData.zones) sensorData.zones = {};
    if (!sensorData.zones[zone]) sensorData.zones[zone] = {};
    
    sensorData.zones[zone].temperature = temperature;
    updateZoneStatus();
    updateSystemOverview();
}

// 更新区域烟雾
function updateZoneSmoke(zone, smoke) {
    if (!sensorData.zones) sensorData.zones = {};
    if (!sensorData.zones[zone]) sensorData.zones[zone] = {};
    
    sensorData.zones[zone].smoke = smoke;
    updateZoneStatus();
    updateSystemOverview();
}

// 绑定操作按钮事件
function bindActionButtons() {
    const buttons = document.querySelectorAll('.action-btn');
    buttons.forEach(button => {
        button.addEventListener('click', function() {
            const action = this.classList.contains('test') ? 'self_test' :
                          this.classList.contains('emergency') ? 'emergency_stop' :
                          this.classList.contains('reset') ? 'reset' :
                          this.classList.contains('report') ? 'generate_report' : '';
            
            if (action && socket) {
                socket.emit('system_action', { action: action });
                
                // 按钮反馈
                this.style.transform = 'scale(0.95)';
                setTimeout(() => {
                    this.style.transform = '';
                }, 150);
            }
        });
    });
}

// 更新日期时间
function updateDateTime() {
    const now = new Date();
    const dateTimeElement = document.getElementById('datetime');
    if (dateTimeElement) {
        dateTimeElement.textContent = now.toLocaleString('zh-CN');
    }
}

// 更新连接状态
function updateConnectionStatus(connected) {
    const statusIndicator = document.querySelector('.status-indicator');
    const statusDot = document.querySelector('.status-dot');
    const statusText = statusIndicator.querySelector('span');
    
    if (connected) {
        statusDot.className = 'status-dot online';
        statusText.textContent = '系统在线';
    } else {
        statusDot.className = 'status-dot offline';
        statusText.textContent = '连接断开';
    }
}

// 显示通知
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.innerHTML = `
        <i class="fas ${getAlarmIcon(type)}"></i>
        <span>${message}</span>
    `;
    
    // 添加样式
    notification.style.cssText = `
        position: fixed;
        top: 100px;
        right: 20px;
        background: linear-gradient(135deg, #1a2332 0%, #0f1419 100%);
        color: white;
        padding: 15px 20px;
        border-radius: 8px;
        border-left: 4px solid ${type === 'danger' ? '#ff4444' : type === 'warning' ? '#ffaa00' : '#00ff88'};
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
        z-index: 1000;
        transform: translateX(100%);
        transition: transform 0.3s ease;
        max-width: 300px;
    `;
    
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
    }, 100);
    
    // 自动隐藏
    setTimeout(() => {
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 5000);
}

// 添加CSS样式到页面
const style = document.createElement('style');
style.textContent = `
    .status-dot.offline {
        background: #ff4444;
        box-shadow: 0 0 10px #ff4444;
    }
    
    .notification {
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .notification i {
        font-size: 1.2rem;
    }
`;
document.head.appendChild(style);

